﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using WinHBM.Core.Bluetooth;
using InTheHand.Net.Sockets;

namespace WinHBM.Core.Net.Sockets.Cmd
{
    public class BluetoothDiscoveryCmd : SocketCmd
    {

        private BluetoothManager bluetoothManager;
        private FlashSocketServer socket;
        private bool found = false;

        public override void executeCmd(JObject request, FlashSocketServer socket)
        {
            this.socket = socket;
            bluetoothManager = new BluetoothManager();
            bluetoothManager.FoundDevice += BluetoothManager_FoundDevice;
            bluetoothManager.DiscoveryCompleted += BluetoothManager_DiscoveryCompleted;
            bluetoothManager.StartDiscovery();
        }

        private void BluetoothManager_DiscoveryCompleted()
        {
            if(!found)
            { 
                socket.Send(wrapCmd(CMD_BLUETOOTH_DISCOVERY, "未找到魔法棒设备"));
            }
        }

        private void BluetoothManager_FoundDevice(BluetoothManager manager, InTheHand.Net.Sockets.BluetoothDeviceInfo device)
        {
            if (device.DeviceName.Equals("BOLUTEK"))
            {
                found = true;
                JObject data = new JObject(); 
                //把mac地址每2位按:分割
                string address = device.DeviceAddress.ToString();
                string[] str = new string[address.Length];
                string temp=""; 
                for (int i = 0; i < address.Length / 2; i++)
                {
                    str[i] = address.Substring(i * 2, 2);
                    temp = temp+ str[i] + ":"; 
                }
                data["address"]  = temp.Substring(0, temp.Length - 1); 
                socket.Send(wrapCmd(CMD_BLUETOOTH_DISCOVERY, data));
            }
        }
    }
}
